package com.example.erhuo.fragment;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.example.erhuo.Good;
import com.example.erhuo.R;
import com.example.erhuo.activity.GoodDetailActivity;
import com.example.erhuo.activity.MainActivity;
import com.example.erhuo.activity.SearchActivity;
import com.example.erhuo.adapter.GoodAdapter;
import com.example.erhuo.api.NetAPI;
import com.example.erhuo.databinding.BuyFragmentBinding;
import com.example.erhuo.databinding.MyFragmentBinding;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.LinkedList;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.RequestBody;
import okhttp3.Response;

public class BuyFragment extends Fragment implements AdapterView.OnItemClickListener, View.OnClickListener, RadioGroup.OnCheckedChangeListener {


    private static String TAG = "BuyFragment";
    private BuyViewModel mViewModel;
    //private MyViewModel myViewModel;

    private RecyclerView recyclerViewBuy;
    private Context mContext;
    private GoodAdapter goodAdapter = null;
    private ListView listGood;
    private Button searchButton;
    private EditText searchEdit;
    private RadioGroup radioGroup;

    public static BuyFragment newInstance() {
        return new BuyFragment();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        mViewModel = ViewModelProviders.of(getActivity()).get(BuyViewModel.class);
        BuyFragmentBinding binding;
        binding = DataBindingUtil.inflate(inflater, R.layout.buy_fragment, container, false);
        View root = binding.getRoot();
        binding.setData(mViewModel);
        binding.setLifecycleOwner(getActivity());

        mContext = getContext();
        initFragment(root);

        if (mViewModel.getGoodAdapter() == null) {
            System.out.println("here adapter is null");
            GoodAdapter goodAdapter = new GoodAdapter(new LinkedList<>(), getContext());
            mViewModel.setGoodAdapter(goodAdapter);
        }
        View footView = inflater.inflate(R.layout.view_tail, null, false);
        listGood.addFooterView(footView);
        if (mViewModel.getGoodAdapter().getCount() == 0 || mViewModel.type != 0) {
            mViewModel.clear();
            getGoods(0, 10, mViewModel.type);
        } else {
            listGood.setAdapter(mViewModel.goodAdapter);
        }


        listGood.setOnItemClickListener(this);
        binding.buyButtonSearch.setOnClickListener(this);
        binding.buyRadioGroup.setOnCheckedChangeListener(this);

        //listGood.setAdapter(goodAdapter);
        return root;

        //return inflater.inflate(R.layout.buy_fragment, container, false);
    }

    private void initFragment(View root) {
        listGood = (ListView) root.findViewById(R.id.buy_good_list);
        searchButton = root.findViewById(R.id.buy_button_search);
        searchEdit = root.findViewById(R.id.buy_edit_search);
        radioGroup = root.findViewById(R.id.buy_radioGroup);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        // TODO Auto-generated method stub
        switch (checkedId) {

            case R.id.radioButton_price_down:
                mViewModel.type = -1;
                break;

            case R.id.radioButton_price_up:
                mViewModel.type = 1;
                break;
            case R.id.radioButton_time_down:
                mViewModel.type = -2;
                break;
            case R.id.radioButton_time_up:
                mViewModel.type = 2;
                break;
            default:
                mViewModel.type = 0;
        }
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //Log.d(TAG,"onActivityCreated");
        //mViewModel = new ViewModelProvider(this).get(BuyViewModel.class);
        // TODO: Use the ViewModel
    }

    private void getGoods(int start, int num, int type) {
        //todo
        RequestBody body = new FormBody.Builder()
                .add("start", "" + start)
                .add("num", "" + num)
                .add("type", "" + type)
                .build();
        Callback callback = new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e(TAG, "获取商品列表失败");
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String information = response.body().string();
                //Log.i(TAG, information);
                JSONObject json;
                try {
                    json = new JSONObject(information);
                    String code = json.getString("code");
                    switch (code) {
                        case "200": {
                            Log.i(TAG, "获取所有商品成功");
                            JSONArray dataJson = json.getJSONObject("data").getJSONArray("goods");
                            for (int i = 0; i < dataJson.length(); i++) {
                                JSONObject object = dataJson.getJSONObject(i);
                                String goodId = object.getString("goodid");
                                String goodStatus = object.getString("goodstatus");
                                String goodTitle = object.getString("goodname");
                                String goodDescription = object.getString("gooddescription");
                                String goodPrice = object.getString("goodprice");
                                String goodCategory = object.getString("goodcategory");
                                String goodSendTime = object.getString("goodsendtime");
                                String goodSenderId = object.getString("goodsenderid");
                                String goodPicUrl = null;
                                try {
                                    goodPicUrl = object.getString("imagePATH");
                                } catch (Exception e) {
                                    Log.e(TAG, "这个商品无图片");
                                }
                                Good good = new Good(goodTitle, goodPrice, goodDescription, goodCategory, goodSendTime, goodStatus, goodSenderId, goodId, goodPicUrl);
                                Callback callback = new Callback() {
                                    @Override
                                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                                        good.setImage(null);
                                    }

                                    @Override
                                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                                        byte[] bytes = response.body().bytes();
                                        Bitmap image = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                                        good.setImage(image);
                                    }
                                };
                                NetAPI.get("api/download/?path=" + goodPicUrl, callback, "");
                                mViewModel.goodAdapter.addGood(good);
                            }
                            Log.i(TAG, "获取了 " + dataJson.length() + " 件商品信息");
                            Log.i(TAG, "目前列表大小：" + mViewModel.goodAdapter.getCount());
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    listGood.setAdapter(mViewModel.goodAdapter);
                                }
                            });
                            break;
                        } default:{
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(getContext(), "获取求购列表失败", Toast.LENGTH_SHORT).show();
                                }
                            });
                            break;
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        };
        NetAPI.postJson("api/GoodOper/searchAllGood/", body, callback);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.buy_button_search: {
                String search = searchEdit.getText().toString();
                if (search.equals("")) {
                    Toast.makeText(getContext(), "请输入关键词", Toast.LENGTH_SHORT).show();
                    return;
                }
                Intent intent = new Intent(getActivity(), SearchActivity.class);
                intent.putExtra("search", search);
                startActivity(intent);
                break;
            }
        }
        //listGood.setAdapter(goodAdapter);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //Log.i(TAG, "你点击了第" + position + "项");
        //Toast.makeText(getContext(), "你点击了第" + position + "项", Toast.LENGTH_SHORT).show();
        if (position == mViewModel.goodAdapter.getCount()) {
            getGoods(mViewModel.goodAdapter.getCount() + 1, 10, mViewModel.type);
            mViewModel.goodAdapter.notifyDataSetChanged();
            return;
        }
        if (MainActivity.token == null || MainActivity.token.equals("")) {
            Toast.makeText(getContext(), "请登录", Toast.LENGTH_SHORT).show();
            return;
        }
        Intent intent = new Intent(getActivity(), GoodDetailActivity.class);
        Good good = (Good) mViewModel.goodAdapter.getItem(position);
        String goodId = good.getId();
        //intent.putExtra("good", good);
        intent.putExtra("goodId", goodId);
        startActivity(intent);
    }

}